package com.ww.idiom.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

import com.ww.core.util.ImageUtil;
import com.ww.core.util.Logger;
import com.ww.core.widget.dialog.MsgDialog;
import com.ww.idiom.R;
import com.ww.idiom.activity.IdiomTask;
import com.ww.idiom.db.IdiomDbHelper;

/**
 * @since 
 * @version 2013-7-11
 * @author wangwei
 */
public class IdiomAdapter extends PagerAdapter {
	private ArrayList<String> list;
	private Context context;
	private int total;

	public IdiomAdapter(Context context, ArrayList<String> list) {
		this.context = context;
		this.list = list;
		total = list.size();
	}

	@Override
	public int getCount() {
		return total;
	}

	@Override
	public boolean isViewFromObject(View view, Object obj) {
		return view == (View) obj;
	}

	@Override
	public Object instantiateItem(ViewGroup container, final int position) {
		View parent = LayoutInflater.from(context).inflate(R.layout.activity_main_item, null);
		
		final Button imageView= (Button)parent.findViewById(R.id.store);
		imageView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				IdiomDbHelper w =new IdiomDbHelper(context);
				String str =w.updateStore(list.get(position));
				if (str.contains("成功")) {
					if (str.contains("取消")) {
						imageView.setText("未收藏");
						Drawable db = ImageUtil.getDrawable(context, R.drawable.icon_tab_store_no);
						db.setBounds(0, 0, db.getMinimumWidth(), db.getMinimumHeight());
						imageView.setCompoundDrawables(db, null, null, null);
						MsgDialog.show(context, "取消收藏成功");
						sendBroadcast();
					} else {
						Drawable db = ImageUtil.getDrawable(context, R.drawable.icon_tab_store_yes);
						db.setBounds(0, 0, db.getMinimumWidth(), db.getMinimumHeight());
						imageView.setCompoundDrawables(db, null, null, null);
						imageView.setText("已收藏");
						MsgDialog.show(context, "收藏成功");
						sendBroadcast();
					}
				} else {
					MsgDialog.show(context, str);
				}
			}
		});
		parent.setTag(list.get(position));
		new IdiomTask(context).execute(parent);
		
		((ViewPager) container).addView(parent, 0);
		Logger.info("adapter:"+position);
		return parent;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		container.removeView((View) object);
	}
	
	private void sendBroadcast(){
		Intent i = new Intent();
		i.setAction("store");
		context.sendBroadcast(i);
	}
	
}
